package com.sfx.handler.security;

import com.alibaba.fastjson.JSON;
import com.sfx.domain.ResponseResult;
import com.sfx.enums.AppHttpCodeEnum;
import com.sfx.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:认证失败处理器
 * User: sfx
 * Date: 2023-07-12
 * Time: 14:58
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //InsufficientAuthenticationException 超时,需要重新登陆
        //BadCredentialsException 用户或密码错误

        //打印异常信息
        authException.printStackTrace();
        //返回我们规定的异常信息格式
        ResponseResult responseResult = null;
        if (authException instanceof BadCredentialsException) {
            //用户或密码错误
            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR,authException.getMessage());
        }else if(authException instanceof InsufficientAuthenticationException) {
            //超时,需要重新登陆
            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else {
            ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证失败");
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(responseResult));
    }
}